//
//  AppDelegate.swift
//  SwiftWeibo
//
//  Created by Lausen on 2017/4/6.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import UserNotifications
import CoreData
import SVProgressHUD
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        setAdditions()
        
        //1:实例化window
        window = UIWindow.init()
        
        window?.backgroundColor = UIColor.white
        
        //2:设置跟控制器
        window?.rootViewController = WBMainViewController()
        
        //3:设置主window并显示
        window?.makeKeyAndVisible()
        
        loadAppInfo()
        
        return true
    }
}

extension AppDelegate{
    
    fileprivate func setAdditions(){
        
        //1:设置提示的最小显示时间
        SVProgressHUD.setMinimumDismissTimeInterval(2)
        
        //2:设置AFN的指示器, 在状态栏上面的菊花
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        
        //3:设置用户的授权
        //取得用户授权,显示通知
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.sound,.carPlay,.alert,.badge]) { (isSucess, error) in
                
                if isSucess{
                    
                    print("用户授权成功")
                }else{
                    
                    print(error ?? "")
                }
            }
        } else {
            
            let notifySettings = UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil)

            UIApplication.shared.registerUserNotificationSettings(notifySettings)
        }
    }    
}

extension AppDelegate{
    
    /// 用来模拟网络加载
    fileprivate func loadAppInfo(){
        
        DispatchQueue.global().async { 
            
            //1:获取url
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil);
            
            //2:将连接的数据转换成data
            let data = NSData(contentsOf: url!)
            
            //2:获取磁盘路径
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            
            //3:拼接一个路径
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            
            //4:将数据保存至磁盘
            data?.write(toFile: jsonPath, atomically: true)
        }
    }
}
